/**
 * Created by 123 on 2017/3/16.
 */
$(document).ready(function(){
    $("#login").click(function (event) {
        if (!event.target.classList.contains("tagoff")) {
            return;
        }
        $("#login").toggleClass("tagoff");
        $("#signup").toggleClass("tagoff");
        $("#loginForm").toggleClass("hidden");
        $("#signupForm").toggleClass("hidden").toggleClass("form-signup-height");
        $("#mainContainer").toggleClass("floatup").toggleClass("wider");
        $("#selectedBar").toggleClass("col-md-offset-2").toggleClass("col-md-offset-8")
            .toggleClass("col-sm-offset-2").toggleClass("col-sm-offset-8")
            .toggleClass("col-xs-offset-2").toggleClass("col-xs-offset-8");
    });
    $(".showPw").click(function(event){
        var pw=$($(event.target).parent().prev());
        var text=$(event.target).children("span");
        if(pw.attr("type")=="password"){
            pw.attr("type","text");
            text.attr("class","glyphicon glyphicon-eye-close");
        }
        else{
            pw.attr("type","password");
            text.attr("class","glyphicon glyphicon-eye-open");
        }
    });
    $("#signup").click(function(event){
        if (!event.target.classList.contains("tagoff")) {
            return;
        }
        $("#login").toggleClass("tagoff");
        $("#signup").toggleClass("tagoff");
        $("#loginForm").toggleClass("hidden");
        $("#signupForm").toggleClass("hidden").toggleClass("form-signup-height");
        $("#mainContainer").toggleClass("floatup").toggleClass("wider");
        $("#selectedBar").toggleClass("col-md-offset-2").toggleClass("col-md-offset-8")
            .toggleClass("col-sm-offset-2").toggleClass("col-sm-offset-8")
            .toggleClass("col-xs-offset-2").toggleClass("col-xs-offset-8");
    });
    $("ul.dropdown-menu > li > a[href='#']").click(function(event){
        var e=$(event.target);
        $(e.parent().parent().parent().prev()).attr("value",e.html());
    });
    //bootstrapValidator Code Area
    $('#loginForm').bootstrapValidator({
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            Email: {
                validators: {
                    notEmpty: {
                        message: 'Email地址不能为空'
                    },
                    emailAddress: {
                        message: 'Email地址不合法'
                    }
                }
            }
        }
    });
    $('#signupForm').bootstrapValidator({
        message: 'This value is not valid',
        feedbackIcons: {/*输入框不同状态，显示图片的样式*/
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {/*验证*/
            signupEmail:{
              validators:{
                  notEmpty:{
                      message:'Email地址不能为空'
                  },
                  regexp:{
                      regexp:/^[A-Za-z0-9]+([-_.][A-Za-z0-9]+)*@([A-Za-z0-9]+[-.])+[A-Za-z0-9]{2,5}$/,
                      message:"Email地址不合法"
                  }
              }
            },
            signupPassword: {
                validators: {
                    notEmpty: {
                        message: '密码不能为空'
                    },
                    identical:{
                        fields: 'confirmPassword',
                        message: '两次输入的密码不一致'
                    },
                    stringLength:{
                        min: 8,
                        max: 20,
                        message: '密码长度在8-20之间'
                    }
                }
            },
            confirmPassword:{
                validators:{
                    notEmpty:{
                        message: '确认密码不能为空'
                    },
                    identical: {
                        field: 'signupPassword',
                        message: '两次输入的密码不一致'
                    },
                    stringLength:{
                        min: 8,
                        max: 20,
                        message: '密码长度在8-20之间'
                    }
                }
            },
            nickname:{
                validators:{
                    notEmpty:{
                        message:"昵称不能为空"
                    },
                    /**regexp:{
                        regexp:"[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]",
                        message:"不得有特殊符号"
                    }**/
                }
            },
            QQ:{
                validators:{
                    notEmpty:{
                        message:"QQ不得为空"
                    },
                    /**regexp:{
                        regexp:"[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]",
                        message:"不得有特殊符号"
                    }**/
                }
            }
        }
    })
    $("#signupButton").click(function(){
        var val=document.getElementById("signupPassword").value;
        document.getElementById("signupPassword").value=encryptPassword(val);
        var email=$("#signupEmail").val();
        $.ajax({
            cache: true,
            type: "POST",
            url:"/accounts/api/register/",//ajax发送地址
            dataType:"json",
            data:JSON.stringify({
                email:$("#signupEmail").val(),
                username:$("#nickname").val(),
                password:$("#signupPassword").val(),
                college:$("#school").val(),
                school:$("#institute").val(),
                qq:$("#QQ").val()
            }),
            async: true,
            processData:false,
            headers: {
                'Accept': 'text/html; q=1.0, */*'
            },
            contentType:"application/json",
            error: function(request,textStatus,errorThrown) {
                alert("HTTP Status Code: "+request.status+"\n"+
                    "Request Readystate: "+request.readyState+"\n"+
                    "Error description: "+errorThrown+"\n"+
                    "Error Status: "+textStatus);
            },
            success: function(data) {
                alert("success"+"\n"+data.token);
                setCookie(email+"_token",data.token,data.expire_in);
                setCookie(email+"_retoken",data.retoken,data.expire_in);
            }
        });
    });
    $("#loginButton").click(function(){
        var val=document.getElementById("inputPassword").value;
        document.getElementById("inputPassword").value=encryptPassword(val);
        $.ajax({
            cache: true,
            type: "POST",
            url:"/accounts/api/login/",//ajax发送地址
            dataType:"json",
            data:JSON.stringify({
                email:$("#inputEmail").val(),
                password:$("#inputPassword").val()
            }),// 你的formid
            processData:false,
            headers: {
                'Accept': 'text/html; q=1.0, */*'
            },
            contentType:"application/json",
            async: true,
            error: function(request,textStatus,errorThrown) {
                alert("HTTP Status Code: "+request.status+"\n"+
                    "Request Readystate: "+request.readyState+"\n"+
                    "Error description: "+errorThrown+"\n"+
                    "Error Status: "+textStatus);

            }
            ,
            success: function(data,textStatus) {
                alert("success"+"\n"+data.toString());
                var tokenData=JSON.parse(data);
                setCookie(email+"_token",data.token,data.expire_in);
                setCookie(email+"_retoken",data.retoken,100000000000);
            }
        });
    });
    function encryptPassword(input){
        var shaObj = new jsSHA("SHA-256", "TEXT");
        shaObj.update(input);
        var hash = shaObj.getHash("B64");
        return hash;
    }
    function setCookie(name,data,expireTime){
        var expireDate=new Date();
        expireDate.setDate(expireDate.getTime()+expireTime);
        var cookieString=name+"="+encodeURIComponent(data)
        +(expireTime==null)?"":(";expires="+expireDate.toGMTString())
        +" path=/"
        +";";
        document.cookie+=cookieString;
    }
    function getCookie(key){
        var start=document.cookie.indexOf(key);
        if(start!=-1){
            var end=document.cookie.indexOf(";",start);
            return decodeURIComponent(document.cookie.substring(start,end));
        }else{
            return null;
        }
    }
});